package org.wishwork.api.allocate.query;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.api.allocate.query.response.AllocateQueryResponse;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 调拨单查询
 * @author: WangYX
 * @create: 2022-04-12 21:17
 * @Version: 1.0.0
 **/

public class AllocateQueryApi extends Api<List<AllocateQueryResponse>, AllocateQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(AllocateQueryApi.class);

    private Context context;

    public AllocateQueryApi(Context context) {
        this.context = context;
    }


    @Override
    protected String query(AllocateQueryRequest allocateQueryRequest) throws Exception {
        String url = "/open/allocate/query";
        Map<String, Object> params = new HashMap<>();
        if (allocateQueryRequest.getSoIds() != null && allocateQueryRequest.getSoIds().size() > 0) {
            params.put("so_ids", allocateQueryRequest.getSoIds());
        }
        if (allocateQueryRequest.getIoIds() != null && allocateQueryRequest.getIoIds().size() > 0) {
            params.put("io_ids", allocateQueryRequest.getIoIds());
        }
        return HttpHelper.sendRequest(allocateQueryRequest, params, url);
    }

    @Override
    protected List<AllocateQueryResponse> process(JSONObject data, AllocateQueryRequest allocateQueryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<AllocateQueryResponse> allocateQueryResponses = datas.toJavaList(AllocateQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = allocateQueryRequest.getPageIndex();
            AllocateQueryRequest build = allocateQueryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<AllocateQueryResponse> business = business(build);
            allocateQueryResponses.addAll(business);
        }
        return allocateQueryResponses;
    }
}
